package com.jv.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jv.entity.Order;
import com.jv.entity.OrderDetail;
import com.jv.entity.R;
import com.jv.properties.WeixinpayProperties;
import com.jv.service.IOrderDetailService;
import com.jv.service.IOrderService;
import com.jv.util.DateUtil;
import com.jv.util.HttpClientUtil;
import com.jv.util.JwtUtils;
import com.jv.util.StringUtil;
import com.jv.util.XmlUtil;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.util.*;

/**
 * @author Jv
 * @version 1.0
 */
@RestController
@Transactional
@RequestMapping("/my/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private WeixinpayProperties weixinpayProperties;

    //创建订单，返回订单号
    @RequestMapping("/create")
    public R create(@RequestBody Order order, @RequestHeader(value = "token") String token) {
        //通过token获取openid
        System.out.println("token=" + token);
        System.out.println("order=" + order);
        //添加订单到数据库
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if (claims != null) {
            System.out.println("openid=" + claims.getId());
            order.setUserId(claims.getId());
        }
        order.setOrderNo("JAVA" + DateUtil.getCurrentDateStr());//订单号
        order.setCreateDate(new Date());
        OrderDetail[] goods = order.getGoods();
        orderService.save(order);
        //添加订单详情到数据库,返回订单号
        for (OrderDetail good : goods) {
            good.setMId(order.getId());
            orderDetailService.save(good);
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNo", order.getOrderNo());
        return R.ok(resultMap);
    }

    //调用统一下单，预支付
    @RequestMapping("/preparePay")
    public R preparePay(@RequestBody String orderNo) throws Exception {
        System.out.println("orderNo=" + orderNo);
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("orderNo", orderNo));

        System.out.println("=======");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appid", weixinpayProperties.getAppid());
        map.put("mch_id", weixinpayProperties.getMch_id());
        map.put("openid", order.getUserId());
        map.put("nonce_str", StringUtil.getRandomString(32)); // 随机串
        map.put("device_info", weixinpayProperties.getDevice_info());
        map.put("notify_url", weixinpayProperties.getNotify_url());
        map.put("trade_type", "JSAPI"); // 交易类型
        map.put("out_trade_no", orderNo);
        map.put("body", "java1234mall商品购买测试");
        // map.put("total_fee", order.getTotalPrice().movePointRight(2));
        map.put("total_fee", 1);  // 1分钱测试
        // map.put("spbill_create_ip", getRemortIP(request)); // 终端IP
        map.put("spbill_create_ip", "127.0.0.1"); // 终端IP
        map.put("sign", getSign(map)); // 签名
        String xml = XmlUtil.genXml(map);
        System.out.println(xml);

        HttpResponse httpResponse = HttpClientUtil.sendXMLDataByPost(weixinpayProperties.getUrl().toString(), xml);
        String httpEntityContent = HttpClientUtil.getHttpEntityContent(httpResponse);
        System.out.println("httpEntityContent:" + httpEntityContent);

        Map resultMap = XmlUtil.doXMLParse(httpEntityContent);  // 解析返回的xml结果
        System.out.println("resultMap=" + resultMap);
//        if (resultMap.get("result_code").equals("SUCCESS")) {
        if (resultMap.get("result_code").equals("FAIL")) {
            // 封装返回值
            Map<String, Object> payMap = new HashMap<String, Object>();
            payMap.put("appId", resultMap.get("appid"));
            payMap.put("nonceStr", StringUtil.getRandomString(32));
            payMap.put("package", "prepay_id=" + resultMap.get("prepay_id"));
            payMap.put("timeStamp", System.currentTimeMillis() / 1000 + "");
            payMap.put("signType", "MD5");
            String paySign = getSign(payMap);
            System.out.println("paySign=" + paySign);
            System.out.println("==========");
            payMap.put("paySign", paySign); // 重新签名
            payMap.put("orderNo", orderNo);
            System.out.println("payMap=" + payMap);

            return R.ok(payMap);
        } else {
            return R.error(500, "系统报错，请联系管理员");
        }
    }

    private String getSign(Map<String, Object> map) {
        StringBuffer sb = new StringBuffer();
        String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
        Arrays.sort(keyArr);//对array排序
        for (int i = 0, size = keyArr.length; i < size; ++i) {
            if ("sign".equals(keyArr[i])) {
                continue;
            }
            sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
        }
        sb.append("key=" + weixinpayProperties.getKey());
        String sign = string2MD5(sb.toString());
        return sign;
    }

    /***
     * MD5加码 生成32位md5码
     */
    private String string2MD5(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 订单查询 type值   0全部订单   1待付款    2待收货    3退款/退货
     * @param type
     * @return
     */
    @RequestMapping("/list")
    public R list(Integer type,Integer page,Integer pageSize) {
        System.out.println("type=" + type);
        List<Order> orderList = null;
        HashMap<String, Object> resultMap = new HashMap<>();

        Page<Order> pageOrder = new Page<>(page,pageSize);//分页需要第几页、每页记录数

        if (type == 0) {    //  全部订单查询
            //orderList = orderService.list(new QueryWrapper<Order>().orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder, new QueryWrapper<Order>().orderByDesc("id"));
            System.out.println("总记录数："+orderResult.getTotal());
            System.out.println("总页数："+orderResult.getPages());
            System.out.println("当前页的数据："+orderResult.getRecords());
            orderList=orderResult.getRecords();
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }else {
            //orderList = orderService.list(new QueryWrapper<Order>().eq("status",type).orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder, new QueryWrapper<Order>().eq("status",type).orderByDesc("id"));
            System.out.println("总记录数："+orderResult.getTotal());
            System.out.println("总页数："+orderResult.getPages());
            System.out.println("当前页的数据："+orderResult.getRecords());
            orderList=orderResult.getRecords();
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }
        resultMap.put("orderList",orderList);
        return R.ok(resultMap);
    }

}


